package com.efruit.struts.action;

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.LookupDispatchAction;

import com.efruit.externalInterfaces.IShopCart;
import com.efruit.struts.form.ShopCartForm;
import com.efruit.to.ShopCartTO;

public class ShopCartAction extends LookupDispatchAction {
	private IShopCart shopcart;

	public IShopCart getShopcart() {
		return shopcart;
	}

	public void setShopcart(IShopCart shopcart) {
		this.shopcart = shopcart;
	}

	@Override
	protected Map getKeyMethodMap() {
		Map map = new HashMap();
		map.put("shopcart.select", "select");
		map.put("shopcart.remove", "remove");
		map.put("shopcart.edit", "edit");
		map.put("shopcart.checkout", "checkout");
		System.out.println("shopcartaction return map");
		return map;
	}

	public ActionForward select(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		ShopCartForm selectForm = (ShopCartForm) form;
		System.out.println("form id:"+selectForm.getId());
		System.out.println("form name:"+selectForm.getName());
		int amount = shopcart.addProduct(selectForm.getId());
		if (amount == 0)
			return mapping.findForward("error");
		Vector<ShopCartTO> infos = shopcart.getShoppingInfo();
		request.getSession().setAttribute("shopcartInfos", infos);
		return mapping.findForward("shopcart");
	}

	public ActionForward remove(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		ShopCartForm selectForm = (ShopCartForm) form;
		shopcart.removeProduct(selectForm.getId());
		Vector<ShopCartTO> infos = shopcart.getShoppingInfo();
		request.getSession().setAttribute("shopcartInfos", infos);
		return mapping.findForward("shopcart");
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return null;
	}
	
	public ActionForward checkout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		request.getSession().setAttribute("total", shopcart.getTotal());
		return mapping.findForward("checkout");
	}
}
